import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db

template.register_template_library('ix.utils.filters')

from ix.notes import Notes

class MainHandler(webapp.RequestHandler):
  def get(self):
    stat = 'ok'
    data = ''
    method = self.request.get('method')
    
    if(method==''):
      stat = 'err'
      errinf = '缺少操作指令'
      data_view = os.path.join(os.path.dirname(__file__), 'view/jsonapi/errinf.json')
      data_values  = {
        'errinf' : errinf
      }
      data = template.render(data_view, data_values)
      
    if(method=='notes.getList'):
      #notes = Notes.all().order('-created')
      notes = db.GqlQuery("SELECT * FROM Notes LIMIT 10 OFFSET 0")
      data_view = os.path.join(os.path.dirname(__file__), 'view/jsonapi/notes.getList.json')
      data_values  = {
        'notes' : notes
      }
      data = template.render(data_view, data_values)

    if(data==''):
      stat = 'err'
      errinf = '未知参数"' + method + '"'
      data_view = os.path.join(os.path.dirname(__file__), 'view/jsonapi/errinf.json')
      data_values  = {
        'errinf' : errinf
      }
      data = template.render(data_view, data_values)
      
    main_view = os.path.join(os.path.dirname(__file__), 'view/jsonapi/main.json')
    main_values = {
      'stat' : stat,
      'data' : data
    }
    #self.response.headers['Content-type'] = 'application/json'
    self.response.out.write(template.render(main_view, main_values))

def main():
  application = webapp.WSGIApplication([('/notes/api', MainHandler)],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
